package com.cloud.school.bus.teacherhelper.modules.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.touchimageview.GalleryViewPager;
import com.android.support.jhf.universalimageloader.core.ImageLoader;
import com.android.support.jhf.universalimageloader.core.ImageLoaderConfiguration;
import com.android.support.jhf.utils.FileUtils;
import com.android.support.jhf.utils.ImageUtil;
import com.android.support.jhf.utils.SDCardToolUtil;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomListDialog;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomListDialog.CustomListDialogItem;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.entitys.UploadFile;
import com.cloud.school.bus.teacherhelper.modules.home.adapter.BigPictureAdapter;
import com.cloud.school.bus.teacherhelper.protocol.download.DownLoadPictureRequest;
import com.cloud.school.bus.teacherhelper.protocol.download.DownLoadPictureResponse;

/**
 * 大图片展示 flag 0默认标题右边是保存，1标题右边是删除图片
 * 
 * @author jiahongfei
 * 
 */
public class BigPictureActivity extends BaseActivity {

	private static final String SAVE_IMG_PATH = UploadPic.SDCARD_ROOT_PATH
			+ "/" + UploadPic.DCIM + "/" + UploadPic.PICTURE_SAVE_FOLDER + "/";

	private GalleryViewPager mViewPager;
	private BigPictureAdapter mBigPictureAdapter;
	private TitleNavBarView mTitleNavBarView;

	private List<Picture> mPictures = new ArrayList<Picture>();
	private int mPosition = 0;
	private int mFlag = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_big_picture);

		init();
	}

	@Override
	protected void init() {
		mFlag = getIntent().getIntExtra("flag", 0);

		mApplication.imageLoaderInit(400, 400);

		mPictures = (List<Picture>) getIntent().getSerializableExtra(
				"pictureList");
		if (null == mPictures) {
			mPictures.add(new Picture());
			mPictures.add(new Picture());
		}
		mPosition = getIntent().getIntExtra("position", 0);

		mViewPager = (GalleryViewPager) findViewById(R.id.viewPager);
		mBigPictureAdapter = new BigPictureAdapter(mContext, mPictures);
		mViewPager.setAdapter(mBigPictureAdapter);
		mViewPager.setCurrentItem(mPosition);

		setTitleNavBar();

		setListener();
	}

	@Override
	protected void setListener() {
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// mTitleNavBarView.setMessage(mHotelImages.get(arg0).name + " "
				// + (arg0 + 1) + "/" + mHotelImages.size());
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	@Override
	protected void setTitleNavBar() {
		mTitleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		mTitleNavBarView.setMessage("");
		mTitleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 返回
				cancel();
			}
		});
		if (0 == mFlag) {
			mTitleNavBarView.setRightButtonImageString(R.drawable.btn_more_xml,
					"", R.color.text_blue);
			mTitleNavBarView
					.setRightButtonOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							if (SDCardToolUtil.isExistSDCard()) {
								showSaveDialog();
							} else {
								HandlerToastUI.getHandlerToastUI(mContext,
										"请插入SD卡");
							}
						}
					});
		} else if (1 == mFlag) {
			mTitleNavBarView.setRightButtonImageString(
					R.drawable.btn_delete_photo_xml, "", R.color.text_blue);
			mTitleNavBarView
					.setRightButtonOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							showDelPicDialog();
						}
					});
		}
	}

	private void showDelPicDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog
				.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog.setMessage(getString(R.string.confirm_delete));
		customAlertDialog.setLeftButton(getString(R.string.yes),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent();
						intent.putExtra("DelPicIndex", mPosition);
						setResult(RESULT_OK, intent);
						cancel();
					}
				});
		customAlertDialog.setRightButton(getString(R.string.no),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
		customAlertDialog.show();
	}

	private void showSaveDialog() {
		CustomListDialog customListDialog = CustomListDialog
				.getCustomListDialog(mContext,
						com.android.support.jhf.R.style.DialogFromDownToUp);
		List<CustomListDialogItem> customListDialogItems = new ArrayList<CustomListDialog.CustomListDialogItem>();
		CustomListDialogItem customListDialogItem1 = new CustomListDialogItem();
		customListDialogItem1.text = getString(R.string.save_photo);
		customListDialogItem1.textColor = mContext.getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem1.textSize = 18;
		customListDialogItems.add(customListDialogItem1);
		customListDialog.setMessage(customListDialogItems);
		customListDialog.setTitle(getString(R.string.save));
		customListDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (0 == arg2) {
					// 保存到相册
					downLoadPicture(mPictures.get(mViewPager.getCurrentItem())
							.getPicturePath());

				}
			}
		});
		customListDialog.show();
	}

	private void downLoadPicture(final String picUrlString) {
		NetworkClient.getNetworkClient().GetRequest(
				new DownLoadPictureRequest(mContext, picUrlString),
				new DownLoadPictureResponse() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] binaryData, HttpResponse response) {
						super.onSuccess(statusCode, headers, binaryData,
								response);
						String fname = picUrlString.substring(picUrlString
								.lastIndexOf("/") + 1);
						fname = SAVE_IMG_PATH + fname;
						final String tempFname = fname;
						final boolean result = savePicture(binaryData,
								new File(fname));
						if (!result) {
							HandlerToastUI
									.getHandlerToastUI(
											mContext,
											getString(R.string.failed_please_try_again));
							return;
						}
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								showTipsDialog(tempFname);
							}
						});
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {
					}
				});
	}

	private boolean savePicture(byte[] imgByte, File file) {
		boolean result = true;
		File pathFile = new File(file.getAbsolutePath().substring(0,
				file.getAbsolutePath().lastIndexOf("/")));
		try {
			if (!pathFile.exists()) {
				try {
					pathFile.mkdirs();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (!file.exists()) {

				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			try {
				fileOutputStream.write(imgByte, 0, imgByte.length);
				fileOutputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
				result = false;
			} finally {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			result = false;
		}
		return result;
	}

	private void showTipsDialog(String savePathString) {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setTitleMessage(getString(R.string.tips));
		customAlertDialog.setMessage(getString(R.string.save_succeed) + ","
				+ getString(R.string.save_path) + "\n" + savePathString);
		customAlertDialog.setLeftButton(getString(R.string.confirm),
				new OnClickListener() {

					@Override
					public void onClick(View v) {

					}
				});
		customAlertDialog.setRightButtonGone();
		customAlertDialog.show();
	}

	private void cancel() {
		mApplication.imageLoaderInit(80, 80);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			cancel();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
